import React, { useState, useRef, useEffect } from 'react';
import { Button } from "./ui/button";
import { Textarea } from "./ui/textarea";
import { useLanguage } from "~/lib/LanguageContext";
import { PaperAirplaneIcon, PaperClipIcon, ClipboardIcon } from '@heroicons/react/24/outline';
import MarkdownViewer from './markdown-viewer';

interface Message {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

interface AIChatProps {
  repoUrl?: string;
  selectedCode?: string;
  selectedDocument?: string;
  onClose?: () => void;
}

export default function AIChat({ 
  repoUrl, 
  selectedCode,
  selectedDocument,
  onClose 
}: AIChatProps) {
  const { t } = useLanguage();
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [clipboardContent, setClipboardContent] = useState<string>('');
  
  // 使用localStorage获取当前选择的模型和API密钥
  const getModelAndApiKey = () => {
    if (typeof window === 'undefined') return { model: 'openai-o3', apiKey: '' };
    
    const model = localStorage.getItem('selected_model') || 'openai-o3';
    const apiKey = localStorage.getItem('api_key') || '';
    
    return { model, apiKey };
  };
  
  // 初始化聊天，添加系统消息
  useEffect(() => {
    // 只有在有仓库URL时才创建聊天
    if (!repoUrl && !selectedCode && !selectedDocument) {
      return;
    }
    
    const systemMessage: Message = {
      role: 'system',
      content: `你是CodeMariner(码海星航)项目的AI助手。只回答与以下GitHub仓库相关的问题: ${repoUrl || '未指定'}。
      如果问题与此仓库无关，请礼貌拒绝回答。${selectedCode ? '用户已选择代码片段进行分析。' : ''}${selectedDocument ? '用户已选择文档内容进行解释。' : ''}`
    };
    
    setMessages([systemMessage]);
    
    // 如果有选中的代码或文档，自动添加一条相关消息
    if (selectedCode) {
      const codeMessage: Message = {
        role: 'assistant',
        content: '已加载代码片段。您可以询问关于这段代码的任何问题。'
      };
      setMessages([systemMessage, codeMessage]);
    } else if (selectedDocument) {
      const docMessage: Message = {
        role: 'assistant',
        content: '已加载文档内容。您可以询问关于这份文档的任何问题。'
      };
      setMessages([systemMessage, docMessage]);
    }
  }, [repoUrl, selectedCode, selectedDocument]);
  
  // 滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);
  
  // 访问用户剪贴板
  const readFromClipboard = async () => {
    try {
      const text = await navigator.clipboard.readText();
      setClipboardContent(text);
      return text;
    } catch (err) {
      console.error('Failed to read clipboard:', err);
      setError('无法访问剪贴板。请确保您授予了剪贴板访问权限。');
      return '';
    }
  };

  // 发送消息到指定的AI模型
  const sendMessage = async () => {
    if (!input.trim() && !clipboardContent) return;
    
    // 获取当前模型和API密钥
    const { model, apiKey } = getModelAndApiKey();
    if (!apiKey) {
      setError('请先设置API密钥');
      return;
    }
    
    const messageContent = clipboardContent 
      ? `${input.trim()}\n\n代码/文本：\n\`\`\`\n${clipboardContent}\n\`\`\``
      : input;
    
    const userMessage: Message = {
      role: 'user',
      content: messageContent
    };
    
    const newMessages = [...messages, userMessage];
    setMessages(newMessages);
    setInput('');
    setClipboardContent('');
    setIsLoading(true);
    setError('');
    
    try {
      const baseUrl = process.env.NEXT_PUBLIC_API_DEV_URL ?? "https://api.codemariner.com";
      let endpoint = model === 'deepseek' 
        ? `${baseUrl}/deepseek/chat` 
        : `${baseUrl}/openai/chat`;
      
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: newMessages.map(msg => ({
            role: msg.role,
            content: msg.content
          })),
          api_key: apiKey,
          model: model,
          repository_url: repoUrl || '',
          code: selectedCode || '',
          document: selectedDocument || ''
        }),
      });
      
      if (!response.ok) {
        throw new Error(`错误: ${response.status}`);
      }
      
      const data = await response.json();
      
      const assistantMessage: Message = {
        role: 'assistant',
        content: data.response || '抱歉，我无法生成回复。'
      };
      
      setMessages([...newMessages, assistantMessage]);
    } catch (err) {
      console.error('发送消息时出错:', err);
      setError(err instanceof Error ? err.message : '发送消息时出错');
    } finally {
      setIsLoading(false);
    }
  };
  
  // 处理输入和发送
  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setInput(e.target.value);
  };
  
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };
  
  return (
    <div className="flex flex-col h-full border-2 border-gray-200 rounded-lg bg-white dark:bg-gray-900 dark:border-gray-700 shadow-lg max-h-[600px]">
      <div className="flex justify-between items-center border-b p-4 dark:border-gray-700">
        <h3 className="font-semibold text-lg">{t("ai_chat")}</h3>
        {onClose && (
          <button 
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
          >
            ✕
          </button>
        )}
      </div>
      
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.slice(1).map((message, index) => (
          <div 
            key={index} 
            className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
          >
            <div 
              className={`max-w-[80%] rounded-lg p-3 ${
                message.role === 'user' 
                  ? 'bg-blue-100 dark:bg-blue-900 dark:text-white' 
                  : 'bg-gray-100 dark:bg-gray-800 dark:text-white'
              }`}
            >
              {message.role === 'assistant' ? (
                <MarkdownViewer content={message.content} className="text-sm" />
              ) : (
                <p className="whitespace-pre-line text-sm">{message.content}</p>
              )}
            </div>
          </div>
        ))}
        {isLoading && (
          <div className="flex justify-start">
            <div className="max-w-[80%] rounded-lg p-3 bg-gray-100 dark:bg-gray-800 dark:text-white">
              <div className="flex space-x-2">
                <div className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '0ms' }}></div>
                <div className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '150ms' }}></div>
                <div className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '300ms' }}></div>
              </div>
            </div>
          </div>
        )}
        {error && (
          <div className="text-center text-red-500 dark:text-red-400">
            {error}
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>
      
      {clipboardContent && (
        <div className="px-4 pb-2">
          <div className="bg-gray-100 dark:bg-gray-800 p-2 rounded-md text-xs overflow-hidden text-gray-700 dark:text-gray-300">
            <div className="flex justify-between items-center mb-1">
              <span className="font-medium">剪贴板内容</span>
              <button
                onClick={() => setClipboardContent('')}
                className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
              >
                ✕
              </button>
            </div>
            <div className="max-h-20 overflow-y-auto">
              <pre className="whitespace-pre-wrap">{clipboardContent}</pre>
            </div>
          </div>
        </div>
      )}
      
      <div className="border-t p-4 dark:border-gray-700">
        <div className="flex space-x-2">
          <Textarea
            value={input}
            onChange={handleInputChange}
            onKeyDown={handleKeyDown}
            placeholder={
              selectedCode 
                ? t("ask_about_code") 
                : selectedDocument 
                  ? t("ask_about_document") 
                  : t("ask_about_repo")
            }
            className="min-h-[60px] resize-none"
            disabled={isLoading}
          />
          <div className="flex flex-col justify-end space-y-2">
            <Button
              onClick={() => void readFromClipboard()}
              className="p-2 w-10 h-10 border-[2px] rounded-md border-black bg-blue-400 text-black shadow-[3px_3px_0_0_#000000] transition-transform hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-blue-300 dark:border-gray-700 dark:bg-blue-600 dark:text-white dark:shadow-[3px_3px_0_0_#1f1f1f] dark:hover:bg-blue-500"
              disabled={isLoading}
              type="button"
            >
              <ClipboardIcon className="h-5 w-5" />
            </Button>
            <Button
              onClick={() => void sendMessage()}
              className="p-2 w-10 h-10 border-[2px] rounded-md border-black bg-blue-400 text-black shadow-[3px_3px_0_0_#000000] transition-transform hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-blue-300 dark:border-gray-700 dark:bg-blue-600 dark:text-white dark:shadow-[3px_3px_0_0_#1f1f1f] dark:hover:bg-blue-500"
              disabled={isLoading || (!input.trim() && !clipboardContent)}
              type="button"
            >
              <PaperAirplaneIcon className="h-5 w-5" />
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
} 